<template>
  <!-- 2. 准备一个举报宽高的DOM容器 -->
  <div class="chart-container" ref="chartRef"></div>
</template>

<script>
export default {
  name: "EchartsChart",
};
</script>

<script setup>
import { onMounted, ref, watch } from "vue";
// 需要下载依赖，解决类型报错
import merge from "lodash/merge";
// 1. 引入echarts
import echarts from "@/plugins/echarts";

const props = defineProps(['option']);

// 公共option
const commonOption = {
  title: {
    left: "center",
    top: 10,
    textStyle: {
      color: "#fff",
      fontSize: 12,
      fontWeight: "bolder",
    },
  },
  xAxis: {
    axisLabel: {
      fontSize: 8,
      color: "rgba(255, 255, 255, 0.6)",
    },
    axisTick: {
      show: false,
    },
    axisLine: {
      show: true,
      lineStyle: {
        color: "rgba(255, 255, 255, .1)",
      },
    },
  },
  yAxis: {
    axisLabel: {
      fontSize: 8,
      color: "rgba(255, 255, 255, 0.6)",
    },
    axisLine: {
      show: true,
      lineStyle: {
        color: "rgba(255, 255, 255, .1)",
      },
    },
    splitLine: {
      lineStyle: {
        color: "rgba(255, 255, 255, .1)",
      },
    },
  },
  grid: {
    containLabel: true,
    left: 10,
    right: 10,
    bottom: 10,
    top: 40,
  },
  tooltip: {
    backgroundColor: "rgba(0, 0, 0, .6)",
    textStyle: {
      color: "#fff",
      fontSize: 8,
    },
    borderWidth: 0,
    trigger: "axis",
  },
  legend: {
    top: 10,
    right: 5,
    textStyle: {
      fontSize: 8,
      color: "#fff",
    },
    itemWidth: 15,
    itemHeight: 8,
  },
};

const chartRef = ref();
let chartInstance

// setup函数相当于beforeCreate和created，此时组件根本没有渲染，获取不到DOM元素
const renderEcharts = () => {
  // 3. 初始化echats实例
  if (!chartInstance) {
    chartInstance = echarts.init(chartRef.value);
  }
  // 4. 定义option，由props接受
  const option = merge(commonOption, props.option);
  // 5. 渲染图表
  chartInstance.setOption(option);
};
// 初始化渲染图表
onMounted(renderEcharts);

// 监视更新重新渲染图表
watch(() => props.option, renderEcharts, { deep: true });
</script>

<style scoped>
.chart-container {
  width: 100%;
  height: 100%;
}
</style>
